/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.admin.sys.controller.portal;

import java.net.URLDecoder;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cory.admin.sys.config.AdminConstants;
import com.cory.admin.sys.domain.AdminPrincipal;
import com.cory.admin.sys.domain.entity.SysResource;
import com.cory.admin.sys.domain.portal.MenuVO;
import com.cory.admin.sys.enums.EResourceType;
import com.cory.admin.sys.service.SysResourceService;
import com.cory.boot.base.BaseController;
import com.cory.boot.domain.bean.Result;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

/**
 * 菜单
 * @author xiongcong
 * @date 2019-02-27
 */
@Controller
@RequestMapping("portal/menu")
public class MenuController extends BaseController {
    @Autowired
    private SysResourceService sysResourceService;
    
    @GetMapping("link")
    @SuppressWarnings("unchecked")
    public String link(HttpServletRequest request, Model model, HttpSession session, Integer menuId, String code, String param) {
        assertNotNull(menuId);
        
        SysResource menu = sysResourceService.getById(menuId);
        assertNotNull(menu);
        String url = menu.getUrl();
        assertNotNull(url);
        
        // 如果code有值，一般都是从首页消息跳转过来的，使用消息的url
        if (StringUtils.isNotBlank(code)) {
            SysResource resource = sysResourceService.getByCode(code);
            url = resource != null ? resource.getUrl() : url;
        }
        
        AdminPrincipal user = (AdminPrincipal)session.getAttribute(AdminConstants.SESSION_USER_INFO);
        
        List<SysResource> resources = (List<SysResource>)session.getAttribute(AdminConstants.SESSION_USER_RESOURCE);
        List<Integer> menuIds = resources.stream().filter(i -> i.getType() == EResourceType.MENU.key).map(i -> i.getId()).collect(Collectors.toList());
        if (!menuIds.contains(menuId)) {
            model.addAttribute("message", "您当前没有权限查看和处理该业务，如有需要请联系当前机构管理员！");
            return "common/message";
        }
        
        if (url.startsWith("http://") || url.startsWith("https://")) {
            if (url.indexOf("?") > 0) {
                url = url += "&token=" + user.getToken();
            } else {
                url = url += "?token=" + user.getToken();
            }
            
            String serverName = request.getServerName();
            System.out.println(serverName);
            if (serverName.indexOf("hmo-") >= 0) {
                int len = url.indexOf("://");
                url = url.substring(0, len + 3) + "hmo-" + url.substring(len + 3);
            }
            if (serverName.indexOf("doctor-") >= 0 && url.indexOf("doctor") < 0) { // ciyun_doctor系统不加doctor-前缀
                int len = url.indexOf("://");
                url = url.substring(0, len + 3) + "doctor-" + url.substring(len + 3);
            }
        }
        
        if (StringUtils.isNotBlank(param)) {
            try {
                param = URLDecoder.decode(param, "utf-8");
                url += (url.indexOf("?") > 0 ? "&" : "?") + param;
            } catch(Exception e) {}
        }
        
        System.out.println("--------跳转url-------" + url);
        return "redirect:" + url;
    }
    
    @RequestMapping("getMenuTree")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Result<?> getMenuTree(HttpSession session) {
        
        AdminPrincipal user = (AdminPrincipal)session.getAttribute(AdminConstants.SESSION_USER_INFO);
        List<SysResource> resources = (List<SysResource>)session.getAttribute(AdminConstants.SESSION_USER_RESOURCE);
        
        List<SysResource> services = resources.stream().filter(i -> i.getType() == EResourceType.SERVICE.key).collect(Collectors.toList());
        List<MenuVO> tree = Lists.newArrayList();
        for (SysResource service : services) {
            MenuVO serviceVO = new MenuVO(service.getId(), service.getName(), service.getCode(), service.getIcon());
            
            List<MenuVO> folderVOs = resources.stream().filter(folder -> folder.getPid().equals(service.getId()))
                    .map(folder -> new MenuVO(folder.getId(), folder.getName(), folder.getCode(), folder.getIcon())).collect(Collectors.toList());
            
            folderVOs.forEach(folder -> {
                List<SysResource> menus = resources.stream().filter(menu -> menu.getPid().equals(folder.getId())).collect(Collectors.toList());
                List<MenuVO> menuVOs = menus.stream().map(i -> new MenuVO(i.getId(), i.getName(), i.getCode(), folder.getIcon())
                            .msgCodes(i.getMsgCode(), user.getTenantId())
                            .url(String.format("/portal/menu/link?menuId=%d", i.getId())))
                            .collect(Collectors.toList());
                folder.setMeuns(menuVOs);
            });
            
            if (folderVOs.size() > 1) {
                serviceVO.meuns = folderVOs;
            } else if (folderVOs.size() == 1) {
                serviceVO.meuns = folderVOs.get(0).getMeuns();
            }
            
            if (serviceVO.meuns != null && serviceVO.meuns.size() > 0) {
                tree.add(serviceVO);
            }
        }
        
        // model 1：一级菜单顶部显示，2：一级菜单左侧展示
        return Result.success("ok", ImmutableMap.of("model", 2, "menus", tree));
    }
}
